package Rangel.common.world.tools;

import math.geom2d.polygon.Polygon2D;
import math.geom2d.polygon.Polygon2DUtils;
import math.geom2d.polygon.SimplePolygon2D;

import java.awt.*;


public class PolygonUtil {

    public static Polygon retainPolygon(Polygon polygon1, Polygon polygon2) {//对多边形与
        double[] xs1 = new double[polygon1.npoints];
        double[] ys1 = new double[polygon1.npoints];
        double[] xs2 = new double[polygon2.npoints];
        double[] ys2 = new double[polygon2.npoints];
        for (int i = 0; i < polygon1.npoints; i++) {
            xs1[i] = polygon1.xpoints[i];
            ys1[i] = polygon1.ypoints[i];
        }
        for (int i = 0; i < polygon2.npoints; i++) {
            xs2[i] = polygon2.xpoints[i];
            ys2[i] = polygon2.ypoints[i];
        }
        math.geom2d.polygon.SimplePolygon2D polygon2D1 = new SimplePolygon2D(xs1, ys1);
        math.geom2d.polygon.SimplePolygon2D polygon2D2 = new SimplePolygon2D(xs2, ys2);

        Polygon2D exclusive = Polygon2DUtils.intersection(polygon2D1, polygon2D2);


        int[] exclusiveXs = new int[exclusive.getVertexNumber()];
        int[] exclusiveYs = new int[exclusive.getVertexNumber()];
        int count = exclusive.getVertexNumber();
        for (int i = 0; i < count; i++) {
            exclusiveXs[i] = (int) exclusive.getVertex(i).getX();
            exclusiveYs[i] = (int) exclusive.getVertex(i).getY();
        }
        return new Polygon(exclusiveXs, exclusiveYs, count);
    }

    public static Polygon union(Polygon polygon1, Polygon polygon2) {//对多边形或
        double[] xs1 = new double[polygon1.npoints];
        double[] ys1 = new double[polygon1.npoints];
        double[] xs2 = new double[polygon2.npoints];
        double[] ys2 = new double[polygon2.npoints];
        for (int i = 0; i < polygon1.npoints; i++) {
            xs1[i] = polygon1.xpoints[i];
            ys1[i] = polygon1.ypoints[i];
        }
        for (int i = 0; i < polygon2.npoints; i++) {
            xs2[i] = polygon2.xpoints[i];
            ys2[i] = polygon2.ypoints[i];
        }
        math.geom2d.polygon.SimplePolygon2D polygon2D1 = new SimplePolygon2D(xs1, ys1);
        math.geom2d.polygon.SimplePolygon2D polygon2D2 = new SimplePolygon2D(xs2, ys2);

        Polygon2D union = Polygon2DUtils.union(polygon2D1, polygon2D2);


        int[] unionXs = new int[union.getVertexNumber()];
        int[] unionYs = new int[union.getVertexNumber()];
        int count = union.getVertexNumber();
        for (int i = 0; i < count; i++) {
            unionXs[i] = (int) union.getVertex(i).getX();
            unionYs[i] = (int) union.getVertex(i).getY();
        }
        return new Polygon(unionXs, unionYs, count);
    }
}
